package com.zwr.sheller.customer.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author LSY
 * @Date 2022/1/13 9:33
 * @Version 1.0
 **/
@Configuration
public class RefundRabbitMQConfiguration {

    // 退款交换机的名称
    public static final String REFUND_EXCHANGE = "refundExchange";
    // 退款队列的名称
    public static final String REFUND_QUEUE = "refundQueue";
    // 退款路由钥匙名称
    public static final String REFUND_ROUTING_KEY = "refundRoutingKey";

    // 死信交换机的名称
    public static final String REFUND_DLX_EXCHANGE = "refundDlxExchange";
    // 死信队列的名称
    public static final String REFUND_DLX_QUEUE = "refundDlxQueue";
    // 死信路由要是名称
    public static final String REFUND_DLX_ROUTING_KEY = "refundDlxRouting";

    // 创建业务交换机
    @Bean(REFUND_EXCHANGE)
    public DirectExchange createRefundExchange() {
        return new DirectExchange(REFUND_EXCHANGE);
    }

    // 创建业务队列
    @Bean(REFUND_QUEUE)
    public Queue createRefundQueue() {
        // 退款队列初始化所必须的配置参数，即绑定死信交换机和死信的路由钥匙
        Map<String, Object> args = new HashMap<>(2);
        args.put("x-dead-letter-exchange", REFUND_DLX_EXCHANGE);
        args.put("x-dead-letter-routing-key", REFUND_DLX_ROUTING_KEY);

        // 第一个参数是队列名
        // 第二个参数是durable，即队列是否持久化，持久化后队列会被存储在磁盘上
        // 第三个参数是exclusive，即队列是否只能被当前连接使用，开启后，连接被关闭后立刻就被删除（优先级高于durable）
        // 第四个参数是autoDelete，即是否自动删除，开启后，当没有生产者或者消费者使用此队列，该队列会自动删除
        // 第五个参数是需要携带的参数，即绑定死信交换机和死信的路由钥匙
        return new Queue(REFUND_QUEUE, true, false, false, args);
    }

    // 绑定业务队列到交换机，同时指定路由钥匙
    @Bean(REFUND_ROUTING_KEY)
    public Binding createRefundBinding() {
        return BindingBuilder
                .bind(createRefundQueue())  // 绑定添加业务队列
                .to(createRefundExchange())  // 绑定添加业务交换机
                .with(REFUND_ROUTING_KEY);  // 绑定添加路由钥匙
    }

    // 创建死信交换机
    @Bean(REFUND_DLX_EXCHANGE)
    public DirectExchange createDlxExchange() {
        return new DirectExchange(REFUND_DLX_EXCHANGE);
    }

    // 创建死信队列
    @Bean(REFUND_DLX_QUEUE)
    public Queue createDlxQueue() {
        return new Queue(REFUND_DLX_QUEUE);
    }

    // 绑定死信队列到死信交换机，同时指定路由钥匙
    @Bean(REFUND_DLX_ROUTING_KEY)
    public Binding createDlxBinding() {
        return BindingBuilder
                .bind(createDlxQueue())
                .to(createDlxExchange())
                .with(REFUND_DLX_ROUTING_KEY);
    }
}
